package com.weituotian.system.dao.impl;

import com.weituotian.system.dao.IUserDao;
import com.weituotian.system.entity.User;
import org.springframework.stereotype.Repository;

import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;

@Repository
public class UserDao extends BaseDao<User, Integer> implements IUserDao {

    @Override
    protected String getEntityName() {
        return "User";
    }

    @Override
    protected String getIdFieldName() {
        return "id";
    }

    @Override
    public User findByLoginName(String loginName) {
        Query query1 = getSession().createQuery("select user from User user where user.loginname=:name");
        query1.setParameter("name", loginName);
        try {
            return (User)query1.getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    @Override
    public User findByEmail(String email) {
        Query query1 = getSession().createQuery("select user from User user where user.email=:email");
        query1.setParameter("email", email);
        try {
            return (User)query1.getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    @Override
    public User findByName(String name) {
        Query query1 = getSession().createQuery("select user from User user where user.name=:name");
        query1.setParameter("name", name);
        try {
            return (User)query1.getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    @Override
    public User loginFindBy(String name) {
        Query query1 = getSession().createQuery("select distinct user from User user where user.name=:name or user.loginname=:name or user.email=:name");
        query1.setParameter("name", name);
        try {
            return (User)query1.getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

}
